package com.elvis.singleton;

/**
 * 线程安全的单例类
 *
 * instance是懒加载的，所以需要同步机制
 *
 * Note: if created by reflection then a singleton will not be created but multiple options in the
 * same classloader
 */
public final class ThreadSafeLazyLoadedIvoryTower {

    private static ThreadSafeLazyLoadedIvoryTower instance;

    private ThreadSafeLazyLoadedIvoryTower() {
        // 在一定情况下防止了反射攻击，但是还是存在通过反射创建出多个实例的可能
        if (instance != null) {
            throw new IllegalStateException("Already initialized.");
        }
    }

    /**
     * 当第一次被调用的时候，instance才会被实例化，懒加载
     *
     * 存在性能问题，每次调用getInstance()的时候，只有一个线程能进入getInstance()方法
     * @return 该类的单例
     */
    public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
        if (instance == null) {
            instance = new ThreadSafeLazyLoadedIvoryTower();
        }
        return instance;
    }
}
